﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using BinAnalysisHelp;
using System.IO;
using XChipTool.Enties;
using XChip_Common;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using NPOI.HSSF.UserModel;
using Newtonsoft.Json;

namespace XChipTool
{
    public partial class binTestForm : DevExpress.XtraEditors.XtraForm
    {
        List<BinBase> blist;
        public binTestForm()
        {
            InitializeComponent();
        }

        private void binbtn_Click(object sender, EventArgs e)
        {
            OpenFileDialog sfd = new OpenFileDialog();
            //设置文件类型 
            sfd.Filter = "导入BIN（*.bin）|*.bin";
            //设置默认文件类型显示顺序 
            sfd.FilterIndex = 1;
            //保存对话框是否记忆上次打开的目录 
            sfd.RestoreDirectory = true;
            if (sfd.ShowDialog() != DialogResult.OK) return;
            string foldPath = Path.GetDirectoryName(sfd.FileName);
            AppHelper.UpdateAppConfig("Folder_Road_Force", foldPath);
            ///读取文件全部内容
            //blist = BinHelp.BinToList(sfd.FileName);
            //int headKey = 0x368;
            ////headLength是包含crc校验的长度，xclist是不包含crc校验
            //int headLength = 0x320;
            //获取存放的开始地址 计算结束地址  赋值类
            //var HeadStartAddr = Convert.ToUInt32("0x" + blist[headKey + 1].original.ToString("X2") + blist[headKey].original.ToString("X2"), 16);
            //var HeadEndAddr = HeadStartAddr + headLength;

            //xc151binparsingManager xcm = new xc151binparsingManager();


            //var xclist = xcm.GetList();

            xc151_exManager xcmex = new xc151_exManager();
            var xclist=  JsonConvert.DeserializeObject<List<xc151binparsing>>(xcmex.GetListToXc151Binparsing()); 
            //blist = BinHelp.BinBaseToNode(blist, xclist);
            BinHelp.OpenBinFile(sfd.FileName, xclist);

            bianhaoLook.Properties.DataSource = BinHelp.shead;
            textBinName.Text = Path.GetFileName(sfd.FileName);
        }

     
       

        private void binTestForm_Load(object sender, EventArgs e)
        {
            bianhaoLook.Properties.DisplayMember = "";
            bianhaoLook.Properties.ValueMember = "";
        }
        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void simpleButton3_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(textEdit1.Text)||string.IsNullOrEmpty(textEdit2.Text))
            {
                MessageBox.Show("地址和值不能为空");
                return;
            }
            if (null== bianhaoLook.EditValue|| bianhaoLook.EditValue.ToString().Contains("请"))
            {
                MessageBox.Show("请选择区域");
                return;
            }
            try
            {

                //BinHelp.SetBinBaseToOriginal(blist, textEdit1.Text, textEdit2.Text, bianhaoLook.EditValue.ToString(), true);

                BinHelp.SetBinUpdateData(ref BinHelp.BinList, textEdit1.Text, textEdit2.Text, (uint)0);
                MessageBox.Show($"已修改地址{textEdit1.Text} 值{textEdit2.Text} 区域  成功！");
            }
            catch (Exception ex )
            {
                MessageBox.Show(ex.Message.ToString()); 
            }
           
        }

        /// <summary>
        /// Bin导出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void simpleButton4_Click(object sender, EventArgs e)
        {
            //int headKey = 0x368;
            //var HeadStartAddr = Convert.ToUInt32("0x" + blist[headKey + 1].original.ToString("X2") + blist[headKey].original.ToString("X2"), 16);
            //List<int> numberssss = new List<int>();
            //for (int i = (int)HeadStartAddr + 0xAC; i < (int)HeadStartAddr + 0xAC + 0x14; i++)
            //{
            //    numberssss.Add(blist[i].original);
            //}
            List<int> numbers = new List<int>();
            for (int i = 0; i < blist.Count(); i++)
            {
                numbers.Add(blist[i].original);
            }
            //numbers.InsertRange(0x7E008, numberssss);
            //string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            //string filePath = Path.Combine(desktopPath, "binaryfile.bin");
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.Filter = "bin文件（*.bin）|*.bin";
            sfd.FileName = "binaryfile";
            if (sfd.ShowDialog() != DialogResult.OK)
            {
                return;
            }
            // 将List序列化保存到文件中
            System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
            using (FileStream fileStream = new FileStream(sfd.FileName, FileMode.Create))
            {
                foreach (int number in numbers)
                {
                    byte[] bytes = BitConverter.GetBytes(number);
                    fileStream.Write(bytes, 0, 1);
                }
            }
        }
        string foldPath = "";
        private void simpleButton1_Click(object sender, EventArgs e)
        {
            OpenFileDialog sfd = new OpenFileDialog();
            //设置文件类型 
            sfd.Filter = "导入BIN（*.bin）|*.txt";
            //设置默认文件类型显示顺序 
            sfd.FilterIndex = 1;
            //保存对话框是否记忆上次打开的目录 
            sfd.RestoreDirectory = true;
            if (sfd.ShowDialog() != DialogResult.OK) return;
            foldPath = sfd.FileName;
            AppHelper.UpdateAppConfig("Folder_Road_Force", foldPath);
        }
        
        private void simpleButton2_Click(object sender, EventArgs e)
        {
            var content = File.ReadAllText(foldPath);
            string baseName = Path.GetFileNameWithoutExtension(foldPath);
            string path = Path.GetDirectoryName(foldPath); // 获取路径 
            string[] splitContent = content.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
            List<string> zhishi = new List<string>();
            zhishi.Add("AHD");
            zhishi.Add("THD");
            zhishi.Add("CHD");
            zhishi.Add("CVBS");
            List<string> shiyu = new List<string>() {"720p25", "720p30","1080p25", "1080p30", "4M12", "4M25", "4M15", "4M30",  "5M20", "5M12", "8M15", "8M12" };
            for (int i = 0; i < zhishi.Count(); i++)
            {
                for (int j = 0; j < shiyu.Count(); j++)
                {
                    string newFilePath = Path.Combine(path, $"datapath_{zhishi[i]}_{shiyu[j]}fps.txt");
                    File.WriteAllText(newFilePath, content);
                    newFilePath = Path.Combine(path, $"sensor_sc2336_setting_{shiyu[j]}fps.txt");
                    File.WriteAllText(newFilePath, content);
                    newFilePath = Path.Combine(path, $"TVE_{zhishi[i]}_{shiyu[j]}fps.txt");
                    File.WriteAllText(newFilePath, content);
                }
                
            }
        }

        private void simpleButton5_Click(object sender, EventArgs e)
        {
            OpenFileDialog sfd = new OpenFileDialog();
            //设置文件类型 
            sfd.Filter = "导入文件（*.xlsx）|*.xlsx";
            //设置默认文件类型显示顺序 
            sfd.FilterIndex = 1;
            //保存对话框是否记忆上次打开的目录 
            sfd.RestoreDirectory = true;
            IWorkbook workbook = null;
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                var filePath = sfd.FileName;
                
                var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
                if (filePath.IndexOf(".xlsx") > 0)
                    workbook = new XSSFWorkbook(fs);
                // 2003版本  
                else if (filePath.IndexOf(".xls") > 0)
                    workbook = new HSSFWorkbook(fs);
                var SList = NPOIOprateExcel.GetSheetName(workbook);
                ISheet sheet = null;
                List<string> dataList = new List<string>();
                //获取到菜单页
                for (int i = 0; i < SList.Count; i++)
                {
                    //if (!SList[i].Contains("TVE")) continue;
                    sheet = workbook.GetSheetAt(i);
                    for (int z = 0; z <= sheet.LastRowNum; z++)
                    {
                        IRow row = sheet.GetRow(z);
                        if (row != null)
                        {
                            StringBuilder sb = new StringBuilder();
                            for (int j = 0; j < row.LastCellNum; j++)
                            {
                                if (j > 0)
                                {
                                    sb.Append("<"); // 使用尖括号号分隔每一列
                                }
                                ICell cell = row.GetCell(j);
                                if (cell != null)
                                {
                                    //处理合并的单元格
                                    cell = MergedCell(cell);
                                    //将单元格中的计算公式转换为值例如A2 = B2 * C2如果用常规的获取方法只能获取到A2的单元格中的计算公式
                                    if (filePath.IndexOf(".xlsx") > 0)
                                    {
                                        XSSFFormulaEvaluator ezz = new XSSFFormulaEvaluator(cell.Sheet.Workbook);
                                        ezz.EvaluateInCell(cell);
                                        sb.Append(cell.ToString());
                                    }
                                    // 2003版本  
                                    else if (filePath.IndexOf(".xls") > 0)
                                    {
                                        HSSFFormulaEvaluator ezz = new HSSFFormulaEvaluator(cell.Sheet.Workbook);
                                        ezz.EvaluateInCell(cell);
                                        sb.Append(cell.ToString());
                                    }
                                    
                                }
                            }
                            dataList.Add(sb.ToString());
                        }
                    }

                }
                var aaa = ExcelExtract(filePath);
                List<ExcelParsecs> ExcelParsecslist = new List<ExcelParsecs>();
                ExcelParsecslist =  ExcelParsecsConversion(dataList);



            }
                
        }
        /// <summary>
        /// 将list转换为 List<ExcelParsecs>
        /// </summary>
        /// <param name="dataList">需要转换的数据</param>
        /// <returns>返回List<ExcelParsecs></returns>
        private List<ExcelParsecs> ExcelParsecsConversion (List<string> dataList)
        {
            List<ExcelParsecs> ExcelParsecslist = new List<ExcelParsecs>();
            //从3开始是为了过滤掉上面没有用的数据
            for (int i = 3; i < dataList.Count(); i++)
            {
                //分割字符串
                List<string> stringList = dataList[i].Split('<').ToList();
                ExcelParsecs excelParsecs = new ExcelParsecs();
                //去除第一条空数据
                stringList.RemoveAt(0);
                for (int j = 0; j < stringList.Count(); j++)
                {
                    #region 赋值
                    switch (j)
                    {
                        case 0:
                            excelParsecs.Out_Format_StandardName = stringList[j];
                            break;
                        case 1:
                            excelParsecs.Out_Format_TimingName = stringList[j];
                            break;
                        case 2:
                            excelParsecs.fps = stringList[j];
                            break;
                        case 3:
                            excelParsecs.sensor_out_Hsize = stringList[j];
                            break;
                        case 4:
                            excelParsecs.sensor_out_Vsize = stringList[j];
                            break;
                        case 5:
                            excelParsecs.sensor_out_Htotal = stringList[j];
                            break;
                        case 6:
                            excelParsecs.sensor_out_Vtotal = stringList[j];
                            break;
                        case 7:
                            excelParsecs.sensor_out_Mclk = stringList[j];
                            break;
                        case 8:
                            excelParsecs.isp_in_Hsize_i = stringList[j];
                            break;
                        case 9:
                            excelParsecs.isp_in_Vsize_i = stringList[j];
                            break;
                        case 10:
                            excelParsecs.isp_in_Htoal_i = stringList[j];
                            break;
                        case 11:
                            excelParsecs.isp_in_Vtotal_i = stringList[j];
                            break;
                        case 12:
                            excelParsecs.isp_in_ISP_Clk = stringList[j];
                            break;
                        case 13:
                            excelParsecs.isp_out_Hsize_o = stringList[j];
                            break;
                        case 14:
                            excelParsecs.isp_out_Vsize_o = stringList[j];
                            break;
                        case 15:
                            excelParsecs.isp_out_Htoal_o = stringList[j];
                            break;
                        case 16:
                            excelParsecs.isp_out_Vtotal_o = stringList[j];
                            break;
                        case 17:
                            excelParsecs.isp_out_ISP_out = stringList[j];
                            break;
                        case 18:
                            excelParsecs.isp_out_TVE_clk = stringList[j];
                            break;
                        case 19:
                            excelParsecs.pll_pll1 = stringList[j];
                            break;
                        case 20:
                            excelParsecs.pll_pll2 = stringList[j];
                            break;
                        case 21:
                            excelParsecs.pll_50 = stringList[j];
                            break;
                        case 22:
                            excelParsecs.pll_51 = stringList[j];
                            break;
                        case 23:
                            excelParsecs.pll_52 = stringList[j];
                            break;
                        case 24:
                            excelParsecs.pll_53 = stringList[j];
                            break;
                        case 25:
                            excelParsecs.xc151_pll_cfg = stringList[j];
                            break;
                        case 26:
                            excelParsecs.crop_en = stringList[j];
                            break;
                        case 27:
                            excelParsecs.scale_sel = stringList[j];
                            break;
                        case 28:
                            excelParsecs.sys_div = stringList[j];
                            break;
                        case 29:
                            excelParsecs.isp_div = stringList[j];
                            break;
                        case 30:
                            excelParsecs.isp_odiv = stringList[j];
                            break;
                        case 31:
                            excelParsecs.rxlp_div = stringList[j];
                            break;
                        case 32:
                            excelParsecs.tve_div = stringList[j];
                            break;
                        case 33:
                            excelParsecs.TVE_xx_setting_c = stringList[j];
                            break;
                        case 34:
                            excelParsecs.TVE_name = stringList[j];
                            break;
                        case 35:
                            excelParsecs.sensor_name = stringList[j];
                            break;
                    }
                    #endregion
                }
                ExcelParsecslist.Add(excelParsecs);
            }

            return ExcelParsecslist;
        }


        /// <summary>
        /// 将表格中的数据转换为 List
        /// </summary>
        /// <param name="filePath">表格完整路径</param>
        /// <returns>返回List<ExcelParsecs></returns>
        private List<string> ExcelExtract(string filePath)
        {
            IWorkbook workbook = null;
            var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
            //判断表格版本
            if (filePath.IndexOf(".xlsx") > 0)
                workbook = new XSSFWorkbook(fs);
            // 2003版本  
            else if (filePath.IndexOf(".xls") > 0)
                workbook = new HSSFWorkbook(fs);
            var SList = NPOIOprateExcel.GetSheetName(workbook);
            ISheet sheet = null;
            List<string> dataList = new List<string>();
            //获取到菜单页
            for (int i = 0; i < SList.Count; i++)
            {
                sheet = workbook.GetSheetAt(i);
                for (int z = 0; z <= sheet.LastRowNum; z++)
                {
                    IRow row = sheet.GetRow(z);
                    if (row != null)
                    {
                        StringBuilder sb = new StringBuilder();
                        for (int j = 0; j < row.LastCellNum; j++)
                        {
                            if (j > 0)
                            {
                                sb.Append("<"); // 使用尖括号号分隔每一列
                            }
                            ICell cell = row.GetCell(j);
                            if (cell != null)
                            {
                                //处理合并的单元格
                                cell = MergedCell(cell);
                                //将单元格中的计算公式转换为值例如A2 = B2 * C2如果用常规的获取方法只能获取到A2的单元格中的计算公式
                                if (filePath.IndexOf(".xlsx") > 0)
                                {
                                    XSSFFormulaEvaluator ezz = new XSSFFormulaEvaluator(cell.Sheet.Workbook);
                                    ezz.EvaluateInCell(cell);
                                    sb.Append(cell.ToString());
                                }
                                // 2003版本  
                                else if (filePath.IndexOf(".xls") > 0)
                                {
                                    HSSFFormulaEvaluator ezz = new HSSFFormulaEvaluator(cell.Sheet.Workbook);
                                    ezz.EvaluateInCell(cell);
                                    sb.Append(cell.ToString());
                                }

                            }
                        }
                        dataList.Add(sb.ToString());
                    }
                }

            }
            return dataList;
        }
        /// <summary>
        /// 读取合并单元格的值
        /// </summary>
        /// <param name="cell">查询的单元格</param>
        /// <returns>返回有数值的单元格</returns>
        private ICell MergedCell(ICell cell)
        {
            if (cell.IsMergedCell)//是否是合并单元格
            {
                for (int i = 0; i < cell.Sheet.NumMergedRegions; i++)//遍历所有的合并单元格
                {
                    var cellRange = cell.Sheet.GetMergedRegion(i);
                    if (cell.ColumnIndex >= cellRange.FirstColumn && cell.ColumnIndex <= cellRange.LastColumn
                        && cell.RowIndex >= cellRange.FirstRow && cell.RowIndex <= cellRange.LastRow)//判断查询的单元格是否在合并单元格内
                    {
                        return cell.Sheet.GetRow(cellRange.FirstRow).GetCell(cellRange.FirstColumn);
                    }
                }
            }
            return cell;
        }


    }
}